package com.hmall.gateway.filter;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author liuyp
 * @since 2025/9/2
 */
@Slf4j
@Component
public class AuthorizeGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 如果本次请求在白名单里：直接放行
        String path = exchange.getRequest().getURI().getPath();
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            //excludePath是ant风格的路径写法，就是：/items/**  两个*表示任意层路径，  /items/* 一个*表示一层
            if (antPathMatcher.match(excludePath, path)) {
                //直接放行
                return chain.filter(exchange);
            }
        }

        //2. 获取本次请求携带的令牌。黑马商城项目时，是在请求头中有一个Authorization，值是令牌
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (token == null || "".equals(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        //3. 校验解析令牌。
        Long userId;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            log.error("令牌解析失败，请重新登录", e);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        //4. 将当前用户id添加到请求头上。从exchange里得到的request和response默认是不能修改的，需要执行mutate()然后才能修改
        exchange.getRequest().mutate().header("user-info", userId.toString());
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
